<template>
  <view class="relative bg-white order-list">
    <nav-bar color="white" bg-color="black" title="会员" show-back></nav-bar>
    <u-row gutter="10rpx" customStyle="padding:8rpx;">
      <u-col span="2">
        <u-button type="primary" @click="startReadCard">
          <text class="iconzhucan iconzhucan-huiyuanka mr-5rpx"></text>
          读卡查询
        </u-button>
        </u-col>
      <u-col span="3">
        <view class="flex justify-center items-center">
         <view class="flex-auto"> 
          <u-search
          shape="square"
          placeholder="请输入会员卡号"
          v-model="filterPam.physicalCardNumber"
          search-icon-size="15rpx"
          @custom="getPageData(true)"
        ></u-search>
         </view>
        </view>
      </u-col>
      <u-col span="3">
        <u-search
          shape="square"
          placeholder="请输入会员姓名"
          v-model="filterPam.customerName"
          search-icon-size="15rpx"
          @custom="getPageData(true)"
        ></u-search>
      </u-col>
      <u-col span="1">
        <u-button
          type="info"
          color="lightgrey"
          @click="(filterPam.customerName = ''), (filterPam.physicalCardNumber = ''), getPageData(true)"
          >清空</u-button
        >
      </u-col>
      <u-col span="1">
        <u-button type="primary" color="orange" @click="addVip">新增会员</u-button>
      </u-col>
    </u-row>
    <u-row>
      <view class="px-12rpx w-full box-border">
        <uni-table :loading="pageStatus.loading" class="table-height" stripe emptyText="暂无更多数据" :border="true">
          <!-- 表头行 -->
          <uni-tr class="thead-tr">
            <uni-th align="center" class="fixed-left">序号</uni-th>
            <uni-th align="center">物理卡号</uni-th>
            <uni-th align="center">姓名</uni-th>
            <uni-th align="center">手机号</uni-th>
            <uni-th align="center">年龄</uni-th>
            <uni-th align="center">办卡类型</uni-th>
            <uni-th align="center">会员卡级别</uni-th>
            <uni-th align="center">历史余额（元）</uni-th>
            <uni-th align="center">商户账户余额（元）</uni-th>
            <uni-th align="center">会员卡号</uni-th>
            <uni-th align="center" class="fixed-right thead">操作</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in orderList" :key="item.buffetOrderId">
            <uni-td align="center" bg-color="white" :fixed="true" >{{ index + 1 }}</uni-td>
            <uni-td align="left">{{ item.physicalCardNumber }}</uni-td>
            <uni-td align="center">{{ item.customerName }}</uni-td>
            <uni-td align="center">{{ item.customerPhone || "-" }}</uni-td>
            <uni-td align="center">{{ item.age || "-" }}</uni-td>
            <uni-td align="center">{{
              getFieldValueByThisDict("membershipCardType", item.membershipCardType, dicts)
            }}</uni-td>
            <uni-td align="center">{{ item.membershipLevelName }}</uni-td>
            <uni-td align="center">{{ formatMoney(item.money) }}</uni-td>
            <uni-td align="center">{{ formatMoney(item.businessMoney) }}</uni-td>
            <uni-td align="center">{{ item.vipCardNum }}</uni-td>
            <uni-td align="center" customClass="tdata" bg-color="white" :fixed="true">
              <view class="flex bg-white">
                <u-button type="info" @click="toDetails(item)">查看</u-button>
                <u-button type="primary" @click="recharge(item)">充值</u-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="pagination-box">
          <uni-pagination
            show-icon
            :page-size="filterPam.size"
            :current="filterPam.current"
            :total="filterPam.total"
            @change="pageChange"
          />
        </view>
      </view>
    </u-row>
    <!-- 通知结果弹窗 -->
    <resultPopup ref="refResultPopup" :show-icon="true"> </resultPopup>

    <nfc-popup ref="refNfcPopup" />
  </view>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, inject } from "vue";
import { getVipAccountList, getCustomerInfoByCard } from "@/api";
import { formatMoney, getFieldValueByThisDict } from "@/utils/util";
import { useStore } from "vuex";
import resultPopup from "@/components/common-popup/result-popup.vue";
import { onShow } from "@dcloudio/uni-app";
import { objToUrlParams } from "@kingon/app-tools";

const refResultPopup = ref(null);
const pageStatus = reactive({
  loading: false,
});

const filterPam = reactive({
  physicalCardNumber: "",
  customerName: "",
  current: 1,
  size: 10,
  total: 0,
});

const orderList = ref([]);

const pageChange = (e) => {
  filterPam.current = e.current;
  getPageData();
};

const getPageData = async (isRelaod = false) => {
  if (isRelaod) {
    filterPam.current = 1;
  }
  pageStatus.loading = true;
  try {
    const pam = {
      ...filterPam,
    };
    const { data, success } = await getVipAccountList(pam);
    console.log(data);
    if (!success) throw new Error("获取数据失败");
    orderList.value = data.records;
    filterPam.total = data.total;
    pageStatus.loading = false;
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

// 全局页面传输数据 （不能放在方法体内）
const globalData:any = inject("$globalData");
const toDetails = (item:any) => {
  // 通过全局数据传递 会员数据 （目前没有完整信息的 会员账户详情接口）

  // console.log("globalData>>",globalData);
  globalData.pageChannel = item;

  // 跳转
  uni.navigateTo({
    url: "./details?id=" + item.customerId,
  });
};

const recharge = (item) => {
  if (item.membershipCardType == 2 &&item.surplusMealNum > 0) {
    return refResultPopup.value.open({
      title: "失败",
      content: "套餐卡有剩余次数，不能充值",
      type: "fail",
      autoClose: true,
    });
  }
  uni.navigateTo({
    url: "./recharge?id=" + /* item.customerAccountId  */ item.customerId,
  });
};

// 读卡
// const disabledReadBtn = ref(false);
const refNfcPopup = ref();
const startReadCard = async () => {
  // if (disabledReadBtn.value) return uni.showToast({ title: "正在读卡中", icon: "none" });
  console.log("开始读卡");
  // disabledReadBtn.value = true;
  try {
    // #ifdef APP
    const card = await refNfcPopup.value.reading();
    // #endif

    console.log("读卡结束", card);
    if (card) {
      filterPam.physicalCardNumber = card;
      getPageData(true);
      // queryMerberInfo(card); 别了，还是赋值搜索框，进行搜索吧
    }
    // disabledReadBtn.value = false;
  } catch (error) {
    console.error("读卡失败", error);
    uni.showToast({ title: "读卡失败", icon: "none" });
    // disabledReadBtn.value = false;
  }
};

// 查询会员信息
/**
 *
 * @param type cardNum 卡号 custId 客户id
 * @param id
 */
//  const queryMerberInfo = async (cardNumber) => {
//   try {
//     // 查询会员信息
//     const { data } = await getCustomerInfoByCard({ physicalCardNumber: cardNumber });
//     if (!data) throw new Error("会员信息不存在");
//     // 查询到直接跳转
//     toDetails(data); （x）

//   } catch (error) {
//     console.error("查询会员信息失败 ->", error.toString());
//     uni.showToast({ title: error?.messages || "查询失败", icon: "none" });
//   }
// };

const store = useStore();

const addVip = () => {
  uni.navigateTo({
    url: "./add",
  });
};

onMounted(async () => {
  getPageData();
});


onShow(() => {

// 从其他页面返回时，重新获取数据 (? 这里只考虑有数据的情况刷新)
if (orderList.value.length > 0) {
  // 重置分页
  filterPam.current = 1;
  // 刷新
  getPageData();
}

});

// 其他自定义字典
const dicts = reactive({
  membershipCardType: [
    { dictValue: "1", dictLabel: "普通办卡" },
    { dictValue: "2", dictLabel: "套餐办卡" },
  ],
});
</script>
<style lang="scss" scoped>
.order-list {
  ::v-deep .u-search__content {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
    margin-right: -10px;
    height: 25rpx;

    // .u-search__content__icon {
    //   display: none;
    // }

    .uni-input-input {
      height: 25rpx;
    }
  }
  ::v-deep .u-search__action {
    background: var(--kui-color-theme);
    max-height: 25rpx;
    height: 25rpx;
    border-radius: 3rpx;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 5rpx;
    font-size: 10rpx;
  }

  ::v-deep .u-button {
    border-radius: 3rpx;
    height: 25rpx;
  }
}

.fixed-left {
  position: sticky;
  background-color: white;
  left: 0;
}

.fixed-right { 
  display: flex;
  position: sticky;
  right: 0;

  &.thead {
    display: block;
    box-shadow: -6px 0px 5px 0px #e7e7e7;
  }

  &.tdata {
    background-color: white;
    box-shadow: -6px 0px 5px 0px #e7e7e7;
  }
  ::v-deep .u-button {
    margin-right: 5rpx;
    height: 20rpx;
  }
}

.thead-tr {
  position: sticky;
  top: 0;
  z-index: 2;
}

.table-height {
  max-height: 70vh;
}

.pagination-box {
  padding: 10rpx;
  display: flex;
  flex-direction: row;
  justify-content: right;
  position: sticky;
  bottom: 0;
  background: white;
}
</style>
